// 排序处理函数
export function handleSort(param_sort?: string, tags?: string[]) {
  const defaultSort = {};
  const sort = param_sort ? JSON.parse(param_sort) : defaultSort;
  delete sort._id;
  if (tags) {
    for (let tag of tags) {
      const flag = tag[0] === '+' || tag[0] === '-';
      const signal = tag[0] === '-' ? -1 : 1;
      tag = flag ? tag.slice(1) : tag;
      if (sort[tag] && typeof sort[tag] !== 'number') {
        // console.log('tag: ->>>', sort[tag]);
        sort[tag] = sort[tag] === 'ascend' ? 1 : -1;
      } else if (!sort[tag]) {
        sort[tag] = signal;
      }
    }
  }

  return { ...sort };
}
export function handleSpace<T>(param: T): T {
  const keys = Object.keys(param);
  for (const key of keys) {
    const temp = param[key];
    if (typeof temp === 'string') {
      param[key] = temp.trim();
      if (param[key] === '') delete param[key];
    } else {
      param[key] = temp;
    }
  }
  return param;
}
// 参数处理函数
// tag 写法：正序 '+createTime' 或 'createTime' 倒序 '-_id'
export function handleParams(params, ...tags: string[]) {
  const data = params.data
    ? JSON.parse(params.data)
    : { current: 1, pageSize: 1000 };
  const sort = handleSort(params.sort, tags);
  if (typeof data.current !== 'number' || Number.isNaN(data.current)) {
    data.current = 1;
  }
  if (typeof data.current !== 'number' || Number.isNaN(data.pageSize)) {
    data.pageSize = 10;
  }
  const { current, pageSize } = data;
  data.current = +current > 100 ? 100 : +current - 1;
  data.pageSize = +pageSize > 1000 ? 50 : +pageSize;
  handleSpace(data);
  return { data, sort };
}
